import React,{Component,Fragment} from 'react';
import TodoItem from './Todoitem';
import './style.css';
import axios from 'axios';

class Todolist extends Component{
    constructor(props){
        super(props) //todolist继承Component,调用一下父类的构造函数
        this.state = {      //负责存储组件里面的数据
            inputValue:'',
            list:[]
        }
        //优化，初始化的时候，this指向就改好
        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleButtonClick = this.handleButtonClick.bind(this);
        this.delItem = this.delItem.bind(this)
    }
    render(){
        return (
            <Fragment>
                <div>
                    <input 
                        className='input'
                        value={this.state.inputValue}
                        onChange ={this.handleInputChange}
                        ref={(input) => {this.input = input}}
                    />
                    <button onClick={this.handleButtonClick}>
                        提交
                    </button>
                </div>
                <ul>
                    {this.getTodoItem()}
                </ul>
            </Fragment>           
        )
    }

    componentDidMount(){//组件挂载完成后
        axios.get('./api/todolist')
            .then((res) => {
                this.setState(()=> ({
                     list: res.data
                }))
            })
            .catch(() =>{alert('err')})
    }

    getTodoItem(){
        return this.state.list.map((item,index)=>{
                    return (
                        <div key={item}>
                            <TodoItem 
                                content={item}
                                index={index}
                                deleteItem={this.delItem}
                            />
                        </div>
                    )
                })
    }
    handleInputChange(e){
        const value = this.input.value;
        this.setState(()=> ({
            inputValue: value
        }))   
    }
    handleButtonClick(){
        this.setState({
            list:[...this.state.list, this.state.inputValue],
            //展开运算符，把以前的list全部展开生成一个新的数组,并和新输入的值组合
            inputValue:''
        })
    }
    delItem(index){
        //删除功能，只操作数据，不操作dom
        const list = [...this.state.list];//拷贝,因为react要求state不能直接改变
        list.splice(index,1);
        this.setState({
            list:list
        })
    }
}
export default Todolist;